package ui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import java.util.Random;

import javax.swing.JComponent;
import javax.swing.SwingUtilities;

import n64.VI;


public class VramDisplay extends JComponent {

	static final int RAND_MAX = 32767;
	
	static long next2 = 1;

	// rand: return pseudo-random integer on 0..32767 
	static int rand2() {
		next2 = (next2 * 1103515245 + 12345) & 0x00000000FFFFFFFFL;
		return (int) (((next2 / 65536) & 0xFFFFFFFFL) % 32768);
	}
	
	Random r = new Random();		
	BufferedImage img;
	int[][] vram;
	int h = 0;
	int w = 0;

	public VramDisplay() {
		
		super();

		vram = new int[240][320];
		h = 240;
		w = 320;
	}
	
	public void setVram(final int[][] vram) {
		this.vram = vram;
	}
	
	public void update() throws InterruptedException, InvocationTargetException {
		
		SwingUtilities.invokeAndWait(
			new Runnable() {
				public void run() {
		
					for(int y=0;y<h;y++) {
						for(int x=0;x<w;x++) {
							vram[y][x] = //(int)(r.nextDouble() * 255);
								(int) (((double)rand2() / (double)(RAND_MAX + 1)) * 255);
						}
					}
					
					//VramDisplay.this.repaint();
				}
			}
		);
	}
	
	@Override
	public void paint(Graphics g) {
	
		//this.setSize(this.getParent().getWidth(), this.getParent().getHeight());
		
		if(vram.length == 0) {
			return;
		}
		
		if(vram[0].length == 0) {
			return;
		}

		/*h = vram.length;
		w = vram[0].length;*/
		
		img = (BufferedImage) this.getParent().createImage(w, h);
		Graphics2D gc = img.createGraphics();
		
		Color nextColor;
		
		for(int y=0;y<h;y++) {
			for(int x=0;x<w;x++) {
				//vram[y][x] = (int)(r.nextDouble() * 255);
				//int val = vram[y][x];
				//gc.setColor(new Color(val,val,val));
				
				nextColor = VI.decodeRGBA8888(n64.MemoryManager.readWord(VI.readWord(VI.VI_ORIGIN) + ((x + (y*h))*4)));
				
				gc.drawLine(x, y, x, y);
			}
		}
		
		g.drawImage(img, 0, 0, this.getParent().getWidth(), this.getParent()
				.getHeight(), this.getParent());
	}
}